//
//  ACFilter.swift
//  app_rn_frontend
//
//  Created by 崔世强 on 2018/6/21.
//  Copyright © 2018年 Facebook. All rights reserved.
//

import Foundation

class ACFilter {
    static let shared = ACFilter()
    private init(){}
    
    private var trie:Trie?
    
    func load(fileName:String) {
        if let dir = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first {
            let fileUrl = dir.appendingPathComponent(fileName)
            do {
                let data = try String(contentsOf:fileUrl,encoding:.utf8)
                let strings = data.components(separatedBy: .newlines)
                let builder = Trie.builder().removeOverlaps().diacriticInsensitive()
                for str in strings {
                    _ = builder.add(keyword: str)
                }
                self.trie = builder.build()
            } catch {
                print(error)
            }
        }
    }
    
    func tokenize(_ str:String) -> [Token] {
        return self.trie?.tokenize(text: str) ?? []
    }
    
    func tokenizeAsHtml(_ str:String) -> String {
        var html = ""
        for token in self.tokenize(str) {
            if token.isMatch {
                html.append("<strong style=\"color:red;\">")
            }
            html.append(token.fragment)
            if token.isMatch {
                html.append("</strong")
            }
        }
        return html
    }
    
    func parse(_ str:String) -> [Emit] {
        return self.trie?.parse(text: str) ?? []
    }
    
    func containsMatch(text: String) -> Bool {
        return self.trie?.containsMatch(text:text) ?? false
    }
    
}
